<template>
  <div class="dashboard page-container">
    <div class="page-header">
      <h2>仪表板</h2>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon work-orders">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.totalWorkOrders }}</h3>
            <p>总工单数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.pendingWorkOrders }}</h3>
            <p>待办工单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon completed">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.completedWorkOrders }}</h3>
            <p>已完成工单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon personnel">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.totalUsers }}</h3>
            <p>总用户数</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <el-card class="chart-card">
        <template #header>
          <h3>工单状态分布</h3>
        </template>
        <div ref="statusChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <h3>最近7天工单趋势</h3>
        </template>
        <div ref="trendChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 快速操作 -->
    <el-card class="quick-actions">
      <template #header>
        <h3>快速操作</h3>
      </template>
      <div class="actions-grid">
        <el-button type="primary" size="large" @click="$router.push('/work-orders/create')">
          <el-icon><Plus /></el-icon>
          新建工单
        </el-button>
        <el-button type="success" size="large" @click="$router.push('/work-orders/pending')">
          <el-icon><Clock /></el-icon>
          查看待办
        </el-button>

        <el-button type="warning" size="large" @click="$router.push('/inventory/materials')">
          <el-icon><Box /></el-icon>
          库存管理
        </el-button>
      </div>
    </el-card>

    <!-- 最近工单 -->
    <el-card class="recent-orders">
      <template #header>
        <div class="card-header">
          <h3>最近工单</h3>
          <el-button link @click="$router.push('/work-orders')">查看全部</el-button>
        </div>
      </template>
      <el-table :data="recentWorkOrders" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="工单号" width="100" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">{{ row.priority }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document,
  Clock,
  Check,
  User,
  Plus,
  Box
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { dashboardApi } from '@/api'

interface Stats {
  totalWorkOrders: number
  pendingWorkOrders: number
  completedWorkOrders: number
  totalUsers: number
}

interface WorkOrder {
  id: number
  title: string
  priority: string
  status: string
  created_at: string
}

const stats = ref<Stats>({
  totalWorkOrders: 0,
  pendingWorkOrders: 0,
  completedWorkOrders: 0,
  totalUsers: 0
})

const recentWorkOrders = ref<WorkOrder[]>([])
const loading = ref(false)
const statusChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()
let statusChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return types[priority] || 'info'
}

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    '待处理': 'warning',
    '处理中': 'primary',
    '已完成': 'success',
    '已取消': 'info'
  }
  return types[status] || 'info'
}

const initCharts = async () => {
  await nextTick()
  
  // 初始化状态分布饼图
  if (statusChartRef.value) {
    statusChart = echarts.init(statusChartRef.value)
  }
  
  // 初始化趋势折线图
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
  }
}

const updateStatusChart = (statusDistribution: any[]) => {
  if (!statusChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '工单状态',
        type: 'pie',
        radius: '50%',
        data: statusDistribution.map(item => ({
          value: item.count,
          name: item.status
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  statusChart.setOption(option)
}

const updateTrendChart = (dailyTrend: any[]) => {
  if (!trendChart) return
  
  const dates = dailyTrend.map(item => item.date)
  const counts = dailyTrend.map(item => item.count)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '工单数量',
        data: counts,
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

const loadDashboardData = async () => {
  loading.value = true
  try {
    // 获取仪表板数据
    const dashboardResponse = await dashboardApi.getStats()
    const dashboardData = dashboardResponse.data
    console.log('Dashboard data received:', dashboardData)
    
    // 更新统计数据
    stats.value = {
      totalWorkOrders: dashboardData.totalWorkOrders || 0,
      pendingWorkOrders: dashboardData.pendingWorkOrders || 0,
      completedWorkOrders: dashboardData.completedWorkOrders || 0,
      totalUsers: dashboardData.totalUsers || 0
    }
    
    // 更新图表
    if (dashboardData.statusDistribution) {
      updateStatusChart(dashboardData.statusDistribution)
    }
    if (dashboardData.dailyTrend) {
      updateTrendChart(dashboardData.dailyTrend)
    }

    // 获取最近工单
    const workOrdersResponse = await dashboardApi.getRecentWorkOrders()
    // 确保返回的是数组
    recentWorkOrders.value = Array.isArray(workOrdersResponse.data) ? workOrdersResponse.data : []
  } catch (error: any) {
    console.error('加载仪表板数据失败:', error)
    // 设置默认值避免错误
    recentWorkOrders.value = []
    stats.value = {
      totalWorkOrders: 0,
      pendingWorkOrders: 0,
      completedWorkOrders: 0,
      totalUsers: 0
    }
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    } else {
      ElMessage.error('加载仪表板数据失败')
    }
  } finally {
    loading.value = false
  }
}

const handleResize = () => {
  statusChart?.resize()
  trendChart?.resize()
}

onMounted(async () => {
  await initCharts()
  loadDashboardData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  statusChart?.dispose()
  trendChart?.dispose()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.work-orders {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #e6a23c, #f0c78a);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #67c23a, #95d475);
}

.stat-icon.personnel {
  background: linear-gradient(135deg, #909399, #b1b3b8);
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.stat-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 8px;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.quick-actions {
  margin-bottom: 24px;
  border-radius: 8px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 10px 0;
}

.recent-orders {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}
</style>